/*
Copyright 2015 shizhefei（LuckyJayce）

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
package com.pkutech.carcasher.content;

import android.text.TextUtils;
import android.util.Log;

import com.pkutech.carcasher.bean.SysMsgResponse;
import com.pkutech.carcasher.db.RealmManager;
import com.pkutech.carcasher.model.SysMsg;
import com.pkutech.carcasher.network.SoapApi;
import com.pkutech.carcasher.utils.CommonUtils;
import com.shizhefei.mvc.IDataCacheLoader;
import com.shizhefei.mvc.IDataSource;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import rx.Subscriber;

public class SysMsgDataSource implements IDataSource<List<SysMsg>>, IDataCacheLoader<List<SysMsg>> {
	private int page = 1;
	private int maxPage = 10;

	List<SysMsg> sysMsgList = new ArrayList<SysMsg>();

	public String date;

	/**
	 * 加载缓存<br>
	 * 注意这个方法执行于UI线程，不要做太过耗时的操作<br>
	 * 每次刷新的时候触发该方法，该方法在DataSource refresh之前执行<br>
	 * 
	 * @param isEmpty
	 *            adapter是否有数据，这个值是adapter.isEmpty()决定
	 * @return 加载的数据，返回后会执行adapter.notifyDataChanged(data, true)<br>
	 *         相当于refresh执行后adapter.notifyDataChanged(data, true)
	 */
	@Override
	public List<SysMsg> loadCache(boolean isEmpty) {
//		if (isEmpty) {
//			List<SelectBookingOrder> selectBookingOrders = RealmManager.findAllSelectBookingOrders();
//			return selectBookingOrders;
//		}
		return null;
	}

	@Override
	public List<SysMsg> refresh() throws Exception {
		return loadData(1);
	}

	@Override
	public List<SysMsg> loadMore() throws Exception {
		return loadData(page + 1);
	}

	private List<SysMsg> loadData(int page) throws Exception {
		// 如果网路出错的话，直接抛异常不会执行后面的获取的语句
		SoapApi.getSysMsg("2", date)
				.subscribe(new Subscriber<SysMsgResponse>() {
					@Override
					public void onCompleted() {

					}

					@Override
					public void onError(Throwable e) {

					}

					@Override
					public void onNext(SysMsgResponse sysMsgResponse) {
						RealmManager.clearSelectBookingOrders();
						sysMsgList.clear();
						if(sysMsgResponse != null && !TextUtils.isEmpty(sysMsgResponse.getStatus()) && "true".equals(sysMsgResponse.getStatus())){
							sysMsgList = sysMsgResponse.getData();
							if(sysMsgList != null && sysMsgList.size() > 0){
								maxPage = CommonUtils.calAllPageCount(sysMsgList.size());
							}
						}
					}
				});
		Log.d("cyy", "maxPage:"+maxPage);
		this.page = page;
		Collections.sort(sysMsgList, new SysMsgComparator());
		return sysMsgList;
	}

	@Override
	public boolean hasMore() {
		return page < maxPage;
	}

	public class SysMsgComparator implements Comparator<SysMsg> {

		/**
		 * 如果o1小于o2,返回一个负数;如果o1大于o2，返回一个正数;如果他们相等，则返回0;
		 */
		@Override
		public int compare(SysMsg o1, SysMsg o2) {
			try {
				Date date1 = CommonUtils.parseDateFromString2(o1.getCreatedate());
				Date date2 = CommonUtils.parseDateFromString2(o2.getCreatedate());
				//对日期字段进行升序，如果欲降序可采用before方法
				if(date1.before(date2)) return 1;
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return -1;
		}

	}
}
